/*
 * main.c
 *
 *  Created on: Oct 1, 2012
 *      Author: minfang
 */

#include <avr/io.h>
#include <avr/iom16.h>

#include <avr/interrupt.h>
#include <util/delay.h>

#include "port_defined.h"
#include "status_define.h"
#include "led_function.h"
#include "ad_convert.h"

volatile unsigned int timer_counter;
volatile unsigned int ad_counter;
volatile unsigned int led_enable;
volatile unsigned int t100,t10,t1;

void set_timer() {
	TCNT1H = 0Xff;
	TCNT1L = 0Xf0;

	// time out = 8000000/128/16= 1/3906.25 second

}

//on timer_event
ISR( TIMER1_OVF_vect)

{

	//reset the interrupt
	set_timer();

	if (led_enable) {
		led_process();
	}

	timer_counter++;

	if((timer_counter & 0xfff) == 0){
		t1++;
		if(t1>15){
			t10++;
			t1=0;
		}

		if(t10>15){
			t100++;
			t10=0;
		}

		if(t100>15){
			t100=0;
		}

		ad_counter++;
		ad_start();

	}



}

void showValue(){
	float  v=(float)current_ad;
	v*=2.56;
	v/=1024;

	int v1=(int)v;

	v-=v1;
	v*=10;
	int v2=(int)v;
	v-=v2;
	v*=10;
	int v3=(int )v;

	led_show(hh, 1, ll>>4, 0,ll&0xf, 0);
}

void init_timer(int startFlag) {

	if (startFlag) {
		set_timer();
	}
	TCCR1B = 0X04; // 256 clock
	TIMSK |= 1 << 2; // time1 interrupt enable

	timer_counter = 0;
}
void sleep() {
	asm("sleep;\n");
}


void ad_readly(){

}

int main(void) {

	// prepare for the digital number led
	init_led();

	led_enable = 1;

	t100=0;
	t10=0;
	t1=0;

	t1=1;

	int i1=0;
	for( i1=0;t1!=0;i1++){
		t1<<=1;
	}

	led_show(2, 1, i1/16, 1, i1%16, 1);
	// initialize for the ad convert
	//init_ads();

	// led is only show 4-5 second after a show key push down, so after the interupt , show led
	//init_show_led_interupt();

	//a timer for
	init_timer(1);
	//Turn on the global interupt
	sei();

	while (1) {
		sleep();

	}

}
